import L from "leaflet";
import AntPathPolyline from "./AntPathPolyline";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const setAntPathPolyline = (map: any, plateNumber: string[]) => {
  // 清除所有定时器
  clearTimeout(mapStore.timer);

  // 清除所有的图层
  const allLayers = map._layers; // 注意：_layers是一个内部属性，可能在未来版本中改变

  // 遍历所有图层，并检查它们是否是L.layerGroup的实例
  for (const layerId in allLayers) {
    const layer = allLayers[layerId];

    // 检查图层是否是L.layerGroup的实例
    if (layer instanceof L.LayerGroup) {
      // 如果是，则从地图上移除它
      map.removeLayer(layer);
    }

    // 注意：对于嵌套的layerGroup（即layerGroup中包含其他layerGroup），
    // 你可能需要递归地处理它们，但上面的代码只处理了一级layerGroup。
  }

  const points1 = [];
  const points2 = [];

  const newPoints1 = [
    [39.898457, 116.391844],
    [39.898595, 116.377947],
    [39.898341, 116.368001],
    [39.898063, 116.357144],
    [39.899095, 116.351934],
    [39.905871, 116.35067],
    [39.922329, 116.3498],
    [39.931017, 116.349671],
    [39.939104, 116.349225],
    [39.942233, 116.34991],
    [39.947263, 116.366892],
    [39.947568, 116.387537],
    [39.947764, 116.401988],
    [39.947929, 116.410824],
    [39.947558, 116.42674],
    [39.9397, 116.427338],
    [39.932404, 116.427919],
    [39.923109, 116.428377],
    [39.907094, 116.429583],
    [39.906858, 116.41404],
    [39.906622, 116.405321],
    [39.906324, 116.394954],
    [39.906308, 116.391264],
    [39.916611, 116.390748],
  ];

  const newPoints2 = JSON.parse(JSON.stringify(newPoints1)).reverse();

  const test1 = new AntPathPolyline();
  const testName1 = AntPathPolyline.generateUniqueChar();

  const test2 = new AntPathPolyline();
  const testName2 = AntPathPolyline.generateUniqueChar();

  let width = 0.25;

  let index = 0;

  mapStore.timer = setInterval(function () {
    if (index < newPoints1.length) {
      points1.push(newPoints1[index]);
      points2.push(newPoints2[index]);
      test1.drawPolyline(
        map,
        points1,
        width,
        AntPathPolyline.polylineStyleConfig[0],
        AntPathPolyline.carIconConfig[0],
        testName1
      );
      test2.drawPolyline(
        map,
        points2,
        width,
        AntPathPolyline.polylineStyleConfig[1],
        AntPathPolyline.carIconConfig[1],
        testName2
      );
      index++;
    } else {
      clearTimeout(mapStore.timer);
    }
  }, 1000);
};

export default setAntPathPolyline;
